package org.example.config;


import org.example.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfiguration {

    @Autowired
    private MyUserDetailService userDetailsService;

    //认证（登录）
    @Autowired ////在方法上使用 Autowired 表示自动调用该方法
    public void configurer(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

//        System.out.println(enpassword1);
//        String enpassword2 = encoder.encode("222222");
//        System.out.println(enpassword2);
//        //先使用内存认证方式 用户名是lisi  passwordEncoder密码加密方式是BCryptPasswordEncoder  密码用22222 用户的授权角色是vip
//        authenticationManagerBuilder
//                .inMemoryAuthentication().
//                passwordEncoder(encoder).
//                withUser("lisi").
//                password(enpassword2).
//                roles("vip");
//        //先使用内存认证方式 用户名是lisi  passwordEncoder密码加密方式是BCryptPasswordEncoder  密码用11111 用户的授权角色是common
//
//        authenticationManagerBuilder
//                .inMemoryAuthentication().
//                passwordEncoder(encoder).
//                withUser("zhangsan").
//                password(enpassword1).
//                roles("common");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(encoder);

    }

    //授权
    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        // //过滤请求
        httpSecurity.authorizeHttpRequests(authorize -> {
                    authorize.requestMatchers("/",
                            "/login", "/detail/common/*", "/login/**").permitAll();//不需要认证和授权
                    authorize.requestMatchers("/detail/vip/*") //vip用户必须登录和授权  如果非vip权限授权的用户 访问 vip资源 security 反馈出403
                            .hasAnyRole("vip")//授权
                            .anyRequest() //任何请求
                            .authenticated();//先认证（登录）
                })
                //自定义页面
                .formLogin(form ->
                        form
                                //登陆访问路径：提交表单之后跳转的地址,可以看作一个中转站，这个步骤就是验证user的一个过程
                                .loginProcessingUrl("/userLogin")
                                .usernameParameter("name")
                                .passwordParameter("pwd")
                                //登陆界面
                                .loginPage("/login")
                                ///forward 跳转注意:不会跳转到之前请求路径
                                .defaultSuccessUrl("/")//登陆成功之后跳转的路径
                                .failureForwardUrl("/login")//失败之后的跳转
                );
        // 错误处理
        //AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
        //AccessDeineHandler 用来解决认证过的用户访问无权限资源时的异常
//           .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
//                .accessDeniedHandler(new CustomAuthenticationEntryPoint())
//        );
        return httpSecurity.build();
    }
}
